#include "SHA256.h"
#include <openssl/evp.h>
#include <iomanip>
#include <sstream>

string SHA256::hash(const string &str)
{
    EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
    if (mdctx == nullptr)
    {
        return "";
    }

    const EVP_MD *md = EVP_sha256();
    if (md == nullptr)
    {
        EVP_MD_CTX_free(mdctx);
        return "";
    }

    if (EVP_DigestInit_ex(mdctx, md, nullptr) <= 0)
    {
        EVP_MD_CTX_free(mdctx);
        return "";
    }

    if (EVP_DigestUpdate(mdctx, str.c_str(), str.length()) <= 0)
    {
        EVP_MD_CTX_free(mdctx);
        return "";
    }

    unsigned int len = EVP_MD_size(md);
    unique_ptr<unsigned char[]> digest(new unsigned char[len]);

    if (EVP_DigestFinal_ex(mdctx, digest.get(), &len) <= 0)
    {
        EVP_MD_CTX_free(mdctx);
        return "";
    }

    EVP_MD_CTX_free(mdctx);

    // 将二进制数据转换为十六进制字符串
    ostringstream hex_stream;
    for (unsigned int i = 0; i < len; ++i)
    {
        hex_stream << setw(2) << setfill('0') << hex << (int)digest[i];
    }

    return hex_stream.str();
}
